use build_migrate::{Converter, cli::Cli, script_runner::ScriptRunner};
use std::path::PathBuf;
use std::process;

fn main() {
    let cli = Cli::new();
    let cmd = Cli::build_command();
    let matches = cmd.get_matches();

    // 处理特殊命令
    if matches.get_flag("list-generators") {
        let converter = Converter::new();
        println!("Available generators:");
        for generator in converter.list_generators() {
            println!("  - {}", generator);
        }
        return;
    }

    // 解析配置
    let mut config = match cli.parse_args(&matches) {
        Ok(config) => config,
        Err(e) => {
            eprintln!("Error parsing configuration: {}", e);
            process::exit(1);
        }
    };

    // 初始化日志
    cli.init_logger(&config.log_level);

    // 验证输入文件存在
    if !config.input_path.exists() {
        eprintln!("Error: Input file does not exist: {}", config.input_path.display());
        process::exit(1);
    }

    // 执行迁移前脚本并捕获环境变量
    if !config.pre_migration_scripts.scripts.is_empty() {
        log::info!("执行迁移前脚本...");
        let script_runner = ScriptRunner::new(
            config.pre_migration_scripts.working_directory.clone(),
            config.pre_migration_scripts.continue_on_error,
        );

        match script_runner.run_scripts(&config.pre_migration_scripts.scripts) {
            Ok(env_vars) => {
                if !env_vars.is_empty() {
                    log::info!("从脚本中捕获了 {} 个环境变量", env_vars.len());
                    // 将捕获的环境变量合并到配置中
                    // 注意：脚本捕获的环境变量优先级低于配置文件中显式设置的映射
                    for (key, value) in env_vars {
                        if !config.environment_variables.mappings.contains_key(&key) {
                            config.environment_variables.mappings.insert(key, value);
                        }
                    }
                }
            }
            Err(e) => {
                eprintln!("Error executing pre-migration scripts: {}", e);
                process::exit(1);
            }
        }
    }

    // 创建转换器并执行转换
    let converter = Converter::with_config(&config);

    // 确定项目根目录
    let project_root = config.project_root.clone().unwrap_or_else(|| {
        std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
    });

    log::info!("Starting conversion...");
    log::info!("Input: {}", config.input_path.display());
    log::info!("Generator: {}", config.generator);
    log::info!("Project root: {}", project_root.display());

    if let Err(e) = converter.convert(
        &config.input_path,
        &config.generator,
        &project_root,
        &config
    ) {
        eprintln!("Error during conversion: {}", e);
        process::exit(1);
    }

    println!("Conversion completed successfully!");
}
